﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blade.Compilation;
using System.IO;

namespace Blade.AotCompiler {
	public sealed class ElfCodeStream : CodeStream {
		Stream baseStream;
		long baseOffset;

		public ElfCodeStream(Stream baseStream, long offset, ElfLinker linker, IMethodBody method)
			: base(linker, method) {
			this.baseStream = baseStream;
			baseOffset = offset;
		}

		public override void Flush() { baseStream.Flush(); }

		public override long Length { get { return baseStream.Length - baseOffset; } }

		public override long Position {
			get { return baseStream.Position - baseOffset; }
			set { baseStream.Position = value + baseOffset; }
		}

		public override int Read(byte[] buffer, int offset, int count) {
			return baseStream.Read(buffer, offset, count);
		}

		public override long Seek(long offset, System.IO.SeekOrigin origin) {
			switch (origin) {
				case SeekOrigin.Begin:
					return baseStream.Seek(offset + baseOffset, SeekOrigin.Begin) - baseOffset;
				case SeekOrigin.Current:
				case SeekOrigin.End:
					return baseStream.Seek(offset, origin) - baseOffset;
				default: throw new NotSupportedException();
			}
		}

		public override void SetLength(long value) {
			baseStream.SetLength(baseOffset + value);
		}

		public override void Write(byte[] buffer, int offset, int count) {
			baseStream.Write(buffer, offset, count);
		}
	}
}
